﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WCYCReader.ViewModels;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using WCYCReader.Models;
using WCYCReader.Main.Core;
using WCYCReader.Main;
using WCYCReader.Utility;

namespace WCYCReader.Pages
{
    public partial class BookCityListPage : PhoneApplicationPage
    {

        private string _category;

        private string _categoryName;

        private bool BookCityLoading;

        private PerformanceProgressBar BookCityProgressBar = new PerformanceProgressBar();

        private BookCityListPage_VM bclp_vm = new BookCityListPage_VM();

        private ScrollBar scrollBar;

        private string _finish = "-1";

        private int _pageSize = 10;

        private int _nextPageNo = 1;

        private bool _hasNext = true;

        public BookCityListPage()
        {
            this.InitializeComponent();
        }

        protected void AddPerformanceProgressBar()
        {
            if (!this.BookCityProgressBar.IsIndeterminate)
            {
                this.BookCityProgressBar.IsIndeterminate = true;
                this.BookCityProgressBar.Foreground = new SolidColorBrush(Colors.Red);
                this.BookCityProgressBar.Height = 20;
            }
        }

        private void BookCity_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result != null)
                {
                    JsonData jsonDatum = new JsonData();
                    jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                    this._hasNext = jsonDatum.@value.hasNext;
                    this._nextPageNo = jsonDatum.@value.nextPageNo;
                    this.bclp_vm.SetBookCityList(jsonDatum);
                }
                else
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                this.BookCityLoading = false;
                this.RemovePerformanceProgressBar();
            });
        }

        private void BookCity_HttpPostClient()
        {
            this.BookCityLoading = true;
            this.AddPerformanceProgressBar();
            Dictionary<string, string> strs = new Dictionary<string, string>()
            {
                { "pn", this._nextPageNo.ToString() },
                { "pageSize", this._pageSize.ToString() },
                { "cat", this._category },
                { "finish", this._finish },
                { "fromWho", "4" }
            };
            HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
            httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/operation/categoryList", UriKind.Absolute));
            httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.BookCity_DownloadStringCompleted);
        }

        private void BookCityListbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.bclp_vm.T_BookCityList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }

        private void ContentGrid_Loaded(object sender, RoutedEventArgs e)
        {
            this.BookCityListbox.ItemsSource = this.bclp_vm.T_BookCityList_VM();
            this.SetListScrollBarValueChanged();
            this.listGrid.Children.Add(this.BookCityProgressBar);
            //this.llsBooksByCategory.ItemsSource = this.bclp_vm.T_BookCityList_VM();
            
        }

        private void ContentGrid_Unloaded(object sender, RoutedEventArgs e)
        {
            this.RemovePerformanceProgressBar();
            this.listGrid.Children.Remove(this.BookCityProgressBar);
            this.scrollBar.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(this.verticalScrollBar_ValueChanged);
            //this.RemovePerformanceProgressBar();
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_BookListPage";
            this._category = base.NavigationContext.QueryString["Category"];
            this._categoryName = base.NavigationContext.QueryString["CategoryName"];
            if (this._categoryName != null && this._category != null && this.bclp_vm.T_BookCityList_VM().Count == 0)
            {
                this.PageTitle.Text = this._categoryName;
                this.BookCity_HttpPostClient();
            }
        }

        protected void RemovePerformanceProgressBar()
        {
            if (this.BookCityProgressBar.IsIndeterminate)
            {
                this.BookCityProgressBar.IsIndeterminate = false;
            }
        }

        private void SetListScrollBarValueChanged()
        {
            foreach (ScrollBar visualChildCollection in GetVisualChild.GetVisualChildCollection<ScrollBar>(this.BookCityListbox))
            {
                if (visualChildCollection.Orientation != System.Windows.Controls.Orientation.Vertical)
                {
                    continue;
                }
                this.scrollBar = visualChildCollection;
                this.scrollBar.ValueChanged += this.verticalScrollBar_ValueChanged;
            }
        }

        private void verticalScrollBar_ValueChanged(object sender, RoutedEventArgs e)
        {
            ScrollBar scrollBar = (ScrollBar)sender;
            object value = scrollBar.GetValue(RangeBase.ValueProperty);
            object obj = scrollBar.GetValue(RangeBase.MaximumProperty);
            if (value != null && obj != null && (double)value + 0.3 > (double)obj && !this.BookCityLoading && this._hasNext)
            {
                this.BookCity_HttpPostClient();
            }
        }

        private void llsBooksByCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //BookList_M item = this.llsBooksByCategory.SelectedItem as BookList_M;
            //if (item != null)
            //{
            //    SettingHelper.SaveInToSettings("BookDetail", item);
            //    NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            //}
        }
    }
}